package com.example.forum.service.imp;

import com.example.forum.common.AppResult;
import com.example.forum.common.ResultCode;
import com.example.forum.exception.ApplicationException;
import com.example.forum.mapper.UserMapper;
import com.example.forum.model.User;
import com.example.forum.service.IUserService;

import com.example.forum.utils.MD5Util;
import com.example.forum.utils.UUIDUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.annotations.Update;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.Date;

@Service
@Slf4j
public class UserServiceImp implements IUserService {
    @Autowired
    private UserMapper userMapper;

    @Override
    public void createNormalUser(User user) {
        //判断输入的用户参数是否为空
        if (user == null) {
            throw new ApplicationException(AppResult.fail(ResultCode.ERROR_IS_NULL));
        }
        //查看当前用户是否为空,防止重复注册
        User existUser = userMapper.selectByUsername(user.getUsername());
        if (existUser != null) {
            //说明用户已经注册
            log.info(ResultCode.FAILED_USER_EXISTS.toString() + "username : " + user.getUsername());
            throw new ApplicationException(AppResult.fail(ResultCode.FAILED_USER_EXISTS));
        }

        //传入默认值
        if (user.getGender() == null) {
            user.setGender((byte) 2);
        }

        //填充其余默认值
        user.setIsAdmin((byte) 0);
        user.setAvatarUrl(null);
        user.setArticleCount(0);
        user.setState((byte) 0);
        user.setDeleteState((byte) 0);

        Date date = new Date();
        user.setCreateTime(date);
        user.setUpdateTime(date);
        int result = userMapper.insertSelective(user);
        if (result != 1) {
            log.info(ResultCode.FAILED_CREATE.toString() + "username:" + user.getUsername());
            throw new ApplicationException(AppResult.fail(ResultCode.FAILED_CREATE));
        }

        log.info("新增用户成功！用户名为：" + user.getUsername());
    }

    @Override
    public User selectByUserName(String username) {
        User user = userMapper.selectByUsername(username);
        return user;
    }

    @Override
    public User login(String username, String password) {
        User user = selectByUserName(username);
        if (user == null) {
            //说明用户没有进行注册
            throw new ApplicationException(AppResult.fail(ResultCode.FAILED_LOGIN));
        }
        //获取盐值
        String salt = user.getSalt();
        //进行密码的校验
        String verifyPassword = MD5Util.md5Salt(password,salt);

        if(!verifyPassword.equals(user.getPassword())){
            throw new ApplicationException(AppResult.fail(ResultCode.FAILED_LOGIN));
        }

        return user;
    }

    @Override
    public User selectById(Long id) {
        User user = userMapper.selectByPrimaryKey(id);
        return user;
    }

    @Override
    public void addOneArticleCountById(Long id) {
        //校验参数
        if(id == null || id <= 0){
            log.warn(ResultCode.FAILED_PARAMS_VALIDATE.toString());
            throw new ApplicationException(AppResult.fail(ResultCode.FAILED_PARAMS_VALIDATE));
        }

        //进行获取对象
        User user = userMapper.selectByPrimaryKey(id);

        //校验这里的对象是否存在
        if(user == null){
            log.warn(ResultCode.ERROR_IS_NULL.toString() + ", user id = " + id);
            // 抛出异常
            throw new ApplicationException(AppResult.fail(ResultCode.ERROR_IS_NULL));
        }

        //然后通过更新这里的文章数量
        User updataUser = new User();
        updataUser.setId(user.getId());
        updataUser.setArticleCount(user.getArticleCount() + 1);

        //更新
        int result = userMapper.updateByPrimaryKeySelective(updataUser);
        if(result != 1){
            log.warn(ResultCode.ERROR_SERVICES.toString());
            throw new ApplicationException(AppResult.fail(ResultCode.ERROR_SERVICES));
        }
    }

    @Override
    public void subOneArticleCountById(Long id) {
        if(id == null || id <= 0){
            log.warn(ResultCode.FAILED_USER_ARTICLE_COUNT.toString());
            throw new ApplicationException(AppResult.fail(ResultCode.FAILED_USER_ARTICLE_COUNT));
        }

        //进行获取对象
        User user = userMapper.selectByPrimaryKey(id);

        //校验这里的对象是否存在
        if(user == null){
            log.warn(ResultCode.ERROR_IS_NULL.toString() + ", user id = " + id);
            // 抛出异常
            throw new ApplicationException(AppResult.fail(ResultCode.ERROR_IS_NULL));
        }

        //构造更新的用户对象
        User updataUser = new User();

        updataUser.setId(user.getId());
        if(user.getArticleCount() == 0){
            updataUser.setArticleCount(0);
        }else {
            updataUser.setArticleCount(user.getArticleCount() - 1);
        }
        //调用服务层更新
        int result = userMapper.updateByPrimaryKeySelective(updataUser);

        if(result != 1){
            log.warn(ResultCode.ERROR_SERVICES.toString());
            throw new ApplicationException(AppResult.fail(ResultCode.ERROR_SERVICES));
        }
    }

    @Override
    public void modifyInfo(User user) {
        //进行校验
        if(user == null || user.getId() == null || user.getId() <= 0){
            log.warn(ResultCode.FAILED_PARAMS_VALIDATE.toString());
            // 抛出异常
            throw new ApplicationException(AppResult.fail(ResultCode.FAILED_PARAMS_VALIDATE));
        }

        //根据id判断用户是否存在
        User exsitUser = userMapper.selectByPrimaryKey(user.getId());
        if(exsitUser == null || exsitUser.getDeleteState() == 1){
            log.warn(ResultCode.FAILED_USER_NOT_EXISTS.toString());
            //抛出异常
            throw new ApplicationException(AppResult.fail(ResultCode.FAILED_USER_NOT_EXISTS));
        }

        //定义一个标志位，如果没有进行修改就默认为false
        boolean check = false;

        //构造修改对象
        User updateUser = new User();
        updateUser.setId(user.getId());

        //对于用户名的校验
        if( StringUtils.hasLength(user.getUsername()) && !user.getUsername().equals(exsitUser.getUsername())){
            //进行昵称是否重复的判断
            User checkUser = userMapper.selectByUsername(user.getUsername());
            //如果输入的名字找到了那么就说明这里的用户已经存在了
            if(checkUser != null){
                log.warn(ResultCode.FAILED_USER_EXISTS.toString());
                // 抛出异常
                throw new ApplicationException(AppResult.fail(ResultCode.FAILED_USER_EXISTS));
            }

            updateUser.setUsername(user.getUsername());
            check = true;
        }

       //对于昵称的校验
        if(StringUtils.hasLength(user.getNickname()) && !user.getNickname().equals(exsitUser.getNickname())){
            //进行昵称是否重复的判断
            User checkUser = userMapper.selectByUsername(user.getUsername());
            //如果输入的名字找到了那么就说明这里的用户昵称已经存在了
            if(checkUser != null){
                log.warn(ResultCode.FAILED_USER_EXISTS.toString());
                // 抛出异常
                throw new ApplicationException(AppResult.fail(ResultCode.FAILED_USER_EXISTS));
            }

            updateUser.setNickname(user.getNickname());
            check = true;
        }

        //进行gender的参数校验
        if(user.getGender() != null && !user.getGender().equals(exsitUser.getGender()) ){
            //进行范围取值
            if(user.getGender() < 0 || user.getGender() > 2){
                updateUser.setGender((byte)2);
            }
            updateUser.setGender(user.getGender());

            check = true;
        }

        //对于邮箱的校验
        if( StringUtils.hasLength(user.getEmail()) && !user.getEmail().equals(exsitUser.getEmail())){
            updateUser.setEmail(user.getEmail());

            check = true;
        }

        //进行phone的校验
        if(StringUtils.hasLength(user.getPhoneNum()) && !user.getPhoneNum().equals(exsitUser.getPhoneNum())){
            updateUser.setPhoneNum(user.getPhoneNum());

            check = true;
        }

        //进行remark的校验
        if(StringUtils.hasLength(user.getRemark()) && !user.getRemark().equals(exsitUser.getRemark())){
            updateUser.setRemark(user.getRemark());

            check = true;
        }

        //进行check的判断
        if(check == false){
            log.warn(ResultCode.FAILED_PARAMS_VALIDATE.toString());
            // 抛出异常
            throw new ApplicationException(AppResult.fail(ResultCode.FAILED_PARAMS_VALIDATE));
        }

        //调用mapper
        int row = userMapper.updateByPrimaryKeySelective(updateUser);
        if(row != 1){
            log.warn(ResultCode.ERROR_SERVICES.toString());
            //抛出异常
            throw new ApplicationException(AppResult.fail(ResultCode.ERROR_SERVICES));
        }
    }

    @Override
    public void modifyPassword(Long id, String newPassword, String oldPassword) {
        if(id == null || id <= 0
                || !StringUtils.hasLength(newPassword)
                || !StringUtils.hasLength(oldPassword)){
            log.warn(ResultCode.FAILED_PARAMS_VALIDATE.toString());
            throw new ApplicationException(AppResult.fail(ResultCode.FAILED_PARAMS_VALIDATE));
        }
        User user = userMapper.selectByPrimaryKey(id);
        //判断用户的状态
        if(user == null || user.getDeleteState() == 1){
            log.warn(ResultCode.FAILED_USER_NOT_EXISTS.toString());
            throw new ApplicationException(AppResult.fail(ResultCode.FAILED_USER_NOT_EXISTS));
        }

        //检验老密码是否正确
        String verifyPassword = MD5Util.md5Salt(oldPassword,user.getSalt());


        if(!user.getPassword().equalsIgnoreCase(verifyPassword) ){
            log.warn(verifyPassword+"   "+user.getPassword());
            log.warn(ResultCode.FAILED_OLD_NEW_PWD_NOT_SAME.toString());
            throw new ApplicationException(AppResult.fail(ResultCode.FAILED_OLD_NEW_PWD_NOT_SAME));
        }

        //修改密码
        String newSalt = UUIDUtil.uuid_32();

        //生成新的密文
        String changePassword = MD5Util.md5Salt(newPassword,newSalt);

        //构造一个修改对象
        User updateUser = new User();
        updateUser.setId(user.getId());
        updateUser.setPassword(changePassword);
        //设置新的盐
        updateUser.setSalt(newSalt);

        Date date = new Date();
        updateUser.setUpdateTime(date); // 更新时间

        //调用mapper
        int row = userMapper.updateByPrimaryKeySelective(updateUser);
        if(row != 1){
            log.warn(ResultCode.ERROR_SERVICES.toString());
            throw new ApplicationException(AppResult.fail(ResultCode.ERROR_SERVICES));
        }
    }

    @Override
    public void updateUserAvatar(Long userId, String avatarUrl) {
        User user = userMapper.selectByPrimaryKey(userId);
        User updateUser = new User();
        updateUser.setId(userId);
        updateUser.setAvatarUrl(avatarUrl);

        int row = userMapper.updateByPrimaryKeySelective(updateUser);
        if(row != 1){
            log.warn(ResultCode.ERROR_SERVICES.toString());
            throw new ApplicationException(AppResult.fail(ResultCode.ERROR_SERVICES));
        }
    }


}
